package GUI;

import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import javax.swing.AbstractButton;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import CommonGui.LengthFilter;
import DataObjects.Bon;
import DataObjects.Menu;
import DataObjects.MetaDataOrder;

import Messages.MessageCheckExistsEmpForClockInOut;
import Messages.MessageCheckExistsEmpForClockInOutReply;
import Messages.MessageGetAllMenues;
import Messages.MessageGetAllMenuesReply;

import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;
import java.io.IOException;

import javax.swing.JLabel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class PfUpdateTable extends JPanel {
	
private Dimension screenSize;
	
private MainMenu mainMenu;
private Vector<Menu> menues;
private Vector<Bon> bones;
private JTextField textField;
private JTextField textFieldNumPersons;
private JTextField textFieldNumChild;
private String tableNo;
private MetaDataOrder metaDataOrder;
private int x;
private int y;
private JLabel waiterName;
private int numOfPersons=(-1);
private int focusFlag=0;

	
	public PfUpdateTable (MainMenu mm, Vector<Menu> m,Vector<Bon> vector,String tableNo,MetaDataOrder metaDataOrder)
	{
		super();
		setBackground(new Color(220, 220, 220));
		screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		this.mainMenu=mm;
		this.menues=m;
		this.bones=vector;
		this.tableNo=tableNo;
		this.metaDataOrder=metaDataOrder;
		this.setLayout(null);
		initialize();
		
	}
	
	
	private void initialize()
	{
		x=screenSize.width;
		y=screenSize.height;
		final VKBDigitsOnly vkbPanel=new VKBDigitsOnly(new Color(200,250,230));
		vkbPanel.setBounds(4*x/8, y/5, 6*x/22, 2*y/5);
		add(vkbPanel);
		
		//--- textField for waiter number
		textField = new VKTextField(mainMenu);
		textField.setHorizontalAlignment(JTextField.RIGHT);
		textField.setFont(new Font("Tahoma", Font.PLAIN, 20));
		AbstractDocument doc = (AbstractDocument) textField.getDocument();
		doc.setDocumentFilter(new LengthFilter(doc.getLength(), 4));
		textField.setBounds(x/5, y/4, x/12, y/20);	
		
		
		textField.getDocument().addDocumentListener(new DocumentListener() {

			@Override
			public void changedUpdate(DocumentEvent arg0) {
				
				
			}

			@Override
			public void insertUpdate(DocumentEvent arg0) {
				Document temp=arg0.getDocument();
				int size=temp.getLength();
				String currText=null;
				int num=0;
				
				try {
					currText=temp.getText(0, size);
				} catch (BadLocationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
				try {
					 num=Integer.parseInt(currText);
				  } catch (NumberFormatException e) {
					  JOptionPane.showMessageDialog(null,"מספר לא תקין");
				  }
				
				if(size==4 && num!=0)         //if the input includes 4 digits we will display the name of the waiter on the screen 
				{
					MessageCheckExistsEmpForClockInOut msgCheck=new MessageCheckExistsEmpForClockInOut(currText);
					try {
						mainMenu.ms.client.sendToServer(msgCheck);
						MessageCheckExistsEmpForClockInOutReply result = (MessageCheckExistsEmpForClockInOutReply)mainMenu.ms.client.GetMessage();
						String name=result.getUserName();
						setNameOnTheScreen(name);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				else
				{
					hindNameOnTheScreen();
				}
			}

			@Override
			public void removeUpdate(DocumentEvent arg0) {				
				
			}			
		});
		textField.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mouseClicked(MouseEvent e)
            {
            	JTextField txt=(JTextField)e.getSource();
            	vkbPanel.setTxt(txt);
            
            }
        });
		add(textField);
		
		
		
		
		//-------------------------------------------------------------- textField for num of persons
		textFieldNumPersons = new JTextField();
		textFieldNumPersons.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		textFieldNumPersons.setFont(new Font("Tahoma", Font.PLAIN, 20));
		textFieldNumPersons.setBounds(x/5, y/3, x/12, y/20);
		textFieldNumPersons.setText(Integer.toString(metaDataOrder.getNumOfPersons()));
		AbstractDocument doc2 = (AbstractDocument) textFieldNumPersons.getDocument();
		doc2.setDocumentFilter(new LengthFilter(doc.getLength(), 3));
		add(textFieldNumPersons);
		textFieldNumPersons.setColumns(10);
		
		
		//---textField for num of children
				textFieldNumChild = new JTextField();
				textFieldNumChild.setText(Integer.toString(metaDataOrder.getNumOfChild()));
				textFieldNumChild.setForeground(new Color(192, 192, 192));		
				textFieldNumChild.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
				textFieldNumChild.setCaretPosition(textFieldNumChild.getText().length());
				textFieldNumChild.setFont(new Font("Tahoma", Font.PLAIN, 20));
				textFieldNumChild.setBounds(x/5,10*y/25, x/12, y/20);
				AbstractDocument doc3 = (AbstractDocument) textFieldNumChild.getDocument();
				doc3.setDocumentFilter(new LengthFilter(doc3.getLength(), 3));
				add(textFieldNumChild);
				textFieldNumChild.setColumns(10);
				textFieldNumChild.addFocusListener(new FocusListener() {
				      public void focusGained(FocusEvent e) {	    
				        JTextField text=(JTextField) e.getSource();
					  	text.setForeground(new Color(0, 0, 0));
				        if(text.getText().equals("0") && focusFlag==0)
				        {
				        	text.setText("");
				        	focusFlag=1;
				        }
				        else
				        {
				        	text.setForeground(new Color(0, 0, 0));
				        }
				      }

				      public void focusLost(FocusEvent e) {
				      JTextField text=(JTextField)e.getSource();
				      if(text.getText().isEmpty())
				      {
				    	text.setText("0");
				  		text.setForeground(new Color(192, 192, 192));
				    	focusFlag=0;
				      }
				      else
				      {
				  		text.setForeground(new Color(0, 0, 0));
				      }		        
				      }
				    });
		
		
		
		
		//----------------------------------------------- create button ok (עידכון)
		
		Icon okIcon = new ImageIcon("ok-icon.png");
		Image img = ((ImageIcon) okIcon).getImage();
		Image newimg = img.getScaledInstance(40, 40,java.awt.Image.SCALE_SMOOTH);
		okIcon = new ImageIcon(newimg);
		JButton btnNewButton = new JButton("עידכן", okIcon);
		btnNewButton.setVerticalTextPosition(AbstractButton.BOTTOM);
		btnNewButton.setHorizontalTextPosition(AbstractButton.CENTER);
		btnNewButton.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, x/85));
		btnNewButton.setBounds(7*x/18, 10*y/19, x/11, y/12);
		btnNewButton.addActionListener(new java.awt.event.ActionListener() 
		   {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{
				String inputEid=textField.getText();	
				try
				{
					numOfPersons=Integer.parseInt(textFieldNumPersons.getText());
				}catch(NumberFormatException e1)
				{
					numOfPersons=-1;
					JOptionPane.showMessageDialog(null,"מספר הסועדים לא תקין");
				}
					if(inputEid.equals(metaDataOrder.getEid()) && numOfPersons>-1)
					{
						metaDataOrder.setNumOfPersons(numOfPersons);
						metaDataOrder.setNumOfChild(Integer.parseInt(textFieldNumChild.getText()));
						mainMenu.getContentPane().remove(((BorderLayout)mainMenu.getContentPane().getLayout()).getLayoutComponent(BorderLayout.CENTER));
						mainMenu.getContentPane().add(new PfManageTableOrderPanel(mainMenu,metaDataOrder.getTid()), BorderLayout.CENTER);					
						mainMenu.getContentPane().validate();
					}
					
					else
					{
						if(inputEid.equals(metaDataOrder.getEid())==false)
						{
						JLabel label_2 = new JLabel("מספר עובד לא תקין");                       //mispar miltsar
						label_2.setBounds(3*x/14, 5*y/11, x/4, y/15);
						label_2.setFont(new Font("Tahoma", Font.BOLD,x/54));
						label_2.setForeground(Color.red);
						add(label_2);
						mainMenu.getContentPane().repaint();
						}
					}
									
			}
		});
		add(btnNewButton);
		
		Icon cancelIcon = new ImageIcon("cancel-icon.png");
		Image imgcancel = ((ImageIcon) cancelIcon).getImage();
		Image newimgcancel = imgcancel.getScaledInstance(40, 40,java.awt.Image.SCALE_SMOOTH);
		cancelIcon = new ImageIcon(newimgcancel);
		JButton btnNewButton_1 = new JButton("ביטול", cancelIcon);
		btnNewButton_1.setVerticalTextPosition(AbstractButton.BOTTOM);
		btnNewButton_1.setHorizontalTextPosition(AbstractButton.CENTER);
		btnNewButton_1
				.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, x/85));
		btnNewButton_1.setBounds(7*x/100, 10*y/19, x/11, y/12);
		btnNewButton_1
		.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				mainMenu.getContentPane()
						.remove(((BorderLayout) mainMenu
								.getContentPane().getLayout())
								.getLayoutComponent(BorderLayout.EAST));
				//for kill thread
				((BorderLayout) mainMenu
						.getContentPane().getLayout())
						.getLayoutComponent(BorderLayout.CENTER).setVisible(false);
				//////////////////////
				mainMenu.getContentPane()
						.remove(((BorderLayout) mainMenu
								.getContentPane().getLayout())
								.getLayoutComponent(BorderLayout.CENTER));
				mainMenu.getContentPane().add(
						new PfScheem_All_Tables(mainMenu),
						BorderLayout.CENTER);
				mainMenu.getContentPane().add(
						new PanelFunctionsTables(mainMenu),
						BorderLayout.EAST);
				mainMenu.getContentPane().validate();

			}
		});
		add(btnNewButton_1);


//--------------------------------------create ptihat shulhan label
JLabel label = new JLabel("עידכן שולחן : "+tableNo);    //ptihat shulhan
label.setForeground(new Color(47, 79, 79));
label.setFont(new Font("Tahoma", Font.BOLD, x/48));
label.setBounds(x/5, y/8, x/4, y/13);
add(label);

JLabel label_1 = new JLabel("\u05DE\u05E1' \u05DE\u05DC\u05E6\u05E8 : ");                       //mispar miltsar
label_1.setBounds(5*x/16, 3*y/11, x/10, y/50);
label_1.setFont(new Font("Tahoma", Font.BOLD, x/68));
add(label_1);


JLabel label_2 = new JLabel("מס' מבוגרים : ");                       
label_2.setBounds(5*x/16, 5*y/14, x/8, y/50);
label_2.setFont(new Font("Tahoma", Font.BOLD, x/68));
add(label_2);

JLabel label_3 = new JLabel("מס' ילדים : ");                       
label_3.setBounds(5*x/16, 5*y/12, x/8, y/50);
label_3.setFont(new Font("Tahoma", Font.BOLD, x/68));
add(label_3);

//---------------------------------------create name of waiter label
waiterName= new JLabel();
waiterName.setBounds(5*x/50, 3*y/11, x/9, y/15);
waiterName.setFont(new Font("Tahoma", Font.BOLD, x/35));
waiterName.setForeground(Color.blue);
waiterName.setVisible(false);
add(waiterName);

}






private void setNameOnTheScreen(String name)
{

if(name.equals("null")==false)
{
waiterName.setText(name);		
waiterName.setVisible(true);
}
}


private void hindNameOnTheScreen()
{
waiterName.setVisible(false);
}




}
